#include "convertformat.h"

ConvertFormat::ConvertFormat(AVPixelFormat src_fmt,
                             AVPixelFormat dst_fmt)
{
    srcFmt = src_fmt;
    dstFmt = dst_fmt;
}

bool ConvertFormat::SetDataSize(int src_w, int src_h,
                                int dst_w, int dst_h)
{
    srcW = src_w;
    srcH = src_h;
    dstW = dst_w;
    dstH = dst_h;

    return true;
}

int ConvertFormat::PrepareConvert()
{
    swsCtx = sws_getContext(srcW, srcH, srcFmt,
                             dstW, dstH, dstFmt,
                             SWS_BILINEAR, NULL,
                             NULL, NULL);
    if(!swsCtx)
    {
        printf("get sws_context failed!\n");
    }
    if(av_image_alloc(src_data, src_linesize,
                      srcW, srcH, srcFmt, 1) < 0)
    {
        printf("alloc src_data failed!\n");
    }
    if((bufSize = av_image_alloc(dst_data, dst_linesize,
                                 dstW, dstH, dstFmt, 1)) < 0)
    {
        printf("alloc dst_data failed!\n");
    }

    return 0;
}

int ConvertFormat::ConvertData(Data::DataPtr& data)
{
    memcpy(src_data[0], data->GetPictureDataPtr(), data->getValidDataSize());
    //std::cout << data->getValidDataSize() << std::endl;
    sws_scale(swsCtx, (const uint8_t * const*)src_data,
              src_linesize, 0, srcH, dst_data, dst_linesize);
    memcpy(data->GetPictureDataPtr(), dst_data[0], bufSize);
    data->setValidDataSize(bufSize);
    //std::cout << bufSize << std::endl;
    return 0;
}


